# embedding_value_demo.py
import os
import numpy as np
from langchain_community.embeddings import DashScopeEmbeddings
from sklearn.metrics.pairwise import cosine_similarity


def demonstrate_embedding_value():
    """演示文本嵌入的核心价值"""

    print("🎯 文本嵌入价值演示")
    print("=" * 50)

    # 初始化嵌入模型
    embeddings = DashScopeEmbeddings(
        model="text-embedding-v1",
        dashscope_api_key=os.getenv("DASHSCOPE_API_KEY")
    )

    # 1. 语义相似性检测
    print("1️⃣ 语义相似性检测：")

    # 招聘相关文本
    job_texts = [
        "高级Java开发工程师",
        "资深Java后端开发",
        "Java架构师",
        "前端React开发工程师",
        "Python数据科学家",
        "UI设计师"
    ]

    # 生成嵌入向量
    job_embeddings = embeddings.embed_documents(job_texts)
    print(f"嵌入向量维度：{job_embeddings}")

    # 查询文本
    query = "Java后端程序员"
    query_embedding = embeddings.embed_query(query)

    print(f"查询：{query}")
    print("相似度排序：")

    # 计算相似度
    similarities = []
    for i, job_text in enumerate(job_texts):
        similarity = cosine_similarity(
            [query_embedding],
            [job_embeddings[i]]
        )[0][0]
        similarities.append((job_text, similarity))

    # 按相似度排序
    similarities.sort(key=lambda x: x[1], reverse=True)

    for job_text, similarity in similarities:
        print(f"   {job_text}: {similarity:.3f}")

    # 2. 跨语言语义理解
    print("\n2️⃣ 跨语言语义理解：")

    multilingual_texts = [
        "Java开发工程师",
        "Java Developer",
        "Software Engineer",
        "程序员",
        "Programmer"
    ]

    multilingual_embeddings = embeddings.embed_documents(multilingual_texts)

    for i, text in enumerate(multilingual_texts):
        similarity = cosine_similarity(
            [query_embedding],
            [multilingual_embeddings[i]]
        )[0][0]
        print(f"   {text}: {similarity:.3f}")

    # 3. 细粒度语义区分
    print("\n3️⃣ 细粒度语义区分：")

    skill_texts = [
        "5年Java开发经验",
        "熟悉Spring Boot框架",
        "精通微服务架构",
        "了解Docker容器化",
        "会做菜和唱歌"  # 无关技能
    ]

    tech_query = "后端开发技能"
    tech_query_embedding = embeddings.embed_query(tech_query)

    skill_embeddings = embeddings.embed_documents(skill_texts)

    print(f"查询：{tech_query}")

    for i, skill_text in enumerate(skill_texts):
        similarity = cosine_similarity(
            [tech_query_embedding],
            [skill_embeddings[i]]
        )[0][0]
        relevance = "🎯 高度相关" if similarity > 0.7 else "⚠️ 相关性低" if similarity > 0.5 else "❌ 不相关"
        print(f"   {skill_text}: {similarity:.3f} {relevance}")


# 运行演示
demonstrate_embedding_value()
